﻿
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace Core.Common
{
    public class WXHelper
    {
        #region 参数
        private HttpClient _httpClient;

        public IConfiguration Configuration { get; }
        public WXHelper(IConfiguration configuration)
        {

            _httpClient = new HttpClient();
            _httpClient.Timeout = TimeSpan.FromSeconds(10);
            Configuration = configuration;
            AppId = Configuration["AppId"];
            mapkey = Configuration["mapkey"];

            WeixinAppSecret = Configuration["WeixinAppSecret"];
            GetAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + AppId + "&secret=" + WeixinAppSecret;
            GetCodeUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + AppId + "&redirect_uri=http://apollo.healthy-community.cn/Home/GetResult" +
            "&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
            GetWXTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + AppId;
            GetUserUrl = "https://api.weixin.qq.com/sns/userinfo?";
            mapurl = "https://apis.map.qq.com/ws/geocoder/v1/";
            GetQrUrl = "https://api.weixin.qq.com/cgi-bin/qrcode/create?";
            Showqrcode = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=";
        }
        public static readonly string Token = "";//与微信公众账号后台的Token设置保持一致，区分大小写。
        public static readonly string EncodingAESKey = "";//与微信公众账号后台的EncodingAESKey设置保持一致，区分大小写。
        public static string AppId { get; set; } //;//与微信公众账号后台的AppId设置保持一致，区分大小写。
        public static string mapkey { get; set; }
        public static string mapurl { get; set; }
        public static string WeixinAppSecret { get; set; }
        public static string GetAccessTokenUrl { get; set; }
        public static string GetCodeUrl { get; set; }
        public static string GetWXTokenUrl { get; set; }
        public static string GetUserUrl { get; set; }
        public static string GetQrUrl { get; set; }
        public static string Showqrcode { get; set; }
        #endregion

        #region
        public async Task<string> GetAccessTokenAsync()
        {
            string fdf = "";
            try
            {
                var result = HttpCarryAsync(GetAccessTokenUrl, HttpMethod.Get).Result;
                fdf = result.ToString();
                JObject jo = JObject.Parse(result.ToString());
                string token = jo["access_token"].ToString();
                return await Task.Run(() => token);
            }
            catch (Exception ex)
            {
                return await Task.Run(() => "错误信息=" + ex.Message + ",GetAccessTokenUrl=" + GetAccessTokenUrl + ",返回值=" + fdf);
            }


        }
        #endregion

        #region 请求get
        private async Task<object> HttpCarryAsync(string url, HttpMethod hm,object option=null)
        {


            HttpRequestMessage httpRequestMessage = new HttpRequestMessage();
            httpRequestMessage.Method = hm;
            httpRequestMessage.RequestUri = new Uri(url);
            var multipartFormDataContent = new MultipartFormDataContent();
            multipartFormDataContent.Add(new StringContent("token"), "Auth");
            //var contentByteContent = new ByteArrayContent(fileBytes);
            //contentByteContent.Headers.Add("Content-Type", "application/octet-stream");
            httpRequestMessage.Content = multipartFormDataContent;
            var response = _httpClient.SendAsync(httpRequestMessage).Result;
            //if (!response.IsSuccessStatusCode)
            //{

            //}

            return await Task.Run(() => response.Content.ReadAsStringAsync().Result);
        }
        #endregion

        #region 获取code
        public async Task<string> GetCode()
        {

            var result = HttpCarryAsync(GetCodeUrl, HttpMethod.Get).Result;
            JObject jo = JObject.Parse(result.ToString());
            string token = jo["access_token"].ToString();
            return await Task.Run(() => token);
        }
        #endregion

        #region 保存活动信息的x y坐标

        public async Task<object> GetAreaXY(string area)
        {
            try
            {
                var result = await HttpCarryAsync(mapurl + "?address=" + area + "&key=" + mapkey, HttpMethod.Get);
                return result;

            }
            catch (Exception ex)
            {

                throw;
            }

        }

        #endregion

        #region 获取授权用户信息的token
        public async Task<WXResponse> GetWXToken(string code)
        {
            JObject josn = new JObject();
            try
            {
                string url = GetWXTokenUrl + "&secret=" + WeixinAppSecret + "&code=" + code + "&grant_type=authorization_code";
                var result = HttpCarryAsync(url, HttpMethod.Get).Result;
                JObject jo = JObject.Parse(result.ToString());
                josn = jo;
                string access_token = jo["access_token"].ToString();
                string expires_in = jo["expires_in"].ToString();
                string refresh_token = jo["refresh_token"].ToString();
                string openid = jo["openid"].ToString();
                string scope = jo["scope"].ToString();
                WXResponse wxr = new WXResponse() { Success = true, access_token = access_token, expires_in = expires_in, refresh_token = refresh_token, openid = openid, scope = scope };
                return await Task.Run(() => wxr);
            }
            catch (Exception ex)
            {

                WXResponse wxr = new WXResponse() { Success = false, msg = ex.Message+ josn };
                return await Task.Run(() => wxr);
            }

        }
        #endregion

        #region 获取用户信息
        public async Task<WXUserResponse> GetUser(string access_token, string openid)
        {
            try
            {
                string url = GetUserUrl + "access_token=" + access_token + "&openid=" + openid + "&lang=zh_CN";
                var result = HttpCarryAsync(url, HttpMethod.Get).Result;
                JObject jo = JObject.Parse(result.ToString());
                string _openid = jo["openid"].ToString();
                string nickname = jo["nickname"].ToString();
                string sex = jo["sex"].ToString();
                string province = jo["province"].ToString();
                string city = jo["city"].ToString();
                string country = jo["country"].ToString();
                string headimgurl = jo["headimgurl"].ToString();
                string privilege = jo["privilege"].ToString();
                WXUserResponse wur = new WXUserResponse() { Success = true, openid = _openid, nickname = nickname, sex = sex, province = province, city = city, country = country, headimgurl = headimgurl, privilege = privilege };
                return await Task.Run(() => wur);
            }
            catch (Exception ex)
            {
                WXUserResponse wur = new WXUserResponse() { Success = false, msg = ex.Message };
                return await Task.Run(() => wur);
            }

        }
        #endregion

        #region 发送模板消息
        [Obsolete]
        //public Task<bool> WXSendTemplateMessage(object data, string skipurl, string openid)
        //{
        //    var templateId = Configuration["templateId"];
        //    AccessTokenContainer.Register(AppId, WeixinAppSecret);//如果不进行注册，则会提示该appid未经注册
        //    string access_token = AccessTokenContainer.GetAccessTokenResult(AppId).access_token;
        //    try
        //    {
        //        TemplateApi.SendTemplateMessage(access_token, openid, templateId, skipurl, data);
        //        return Task.Run(() => true);
        //    }
        //    catch (Exception ex)
        //    {
        //        return Task.Run(() => true);
        //    }

        //}


        #endregion

        #region 自定义菜单
        //public Task<bool> CustomMenu() {
        //    ButtonGroup bg = new ButtonGroup();

        //    //单击
        //    //bg.button.Add(new SingleClickButton()
        //    //{
        //    //    name = "瑞影码头",
        //    //    key = "OneClick",
        //    //    type =MenuButtonType.click.ToString()
        //    //});
        //    var subButton = new SubButton()
        //    {
        //        name = "瑞影码头"
        //    };            
        //    subButton.sub_button.Add(new SingleViewButton()
        //    {
        //        url = "http://ryh.yun-ju.com.cn/ImageCircle/index",
        //        name = "影像资讯"
        //    });
        //    subButton.sub_button.Add(new SingleViewButton()
        //    {
        //        url = "http://ryh.yun-ju.com.cn/BloodCessel/Index",
        //        name = "心脑同治"
        //    });
        //    subButton.sub_button.Add(new SingleViewButton()
        //    {
        //        url = "http://mrim.ran-wei.cn",
        //        name = "MRI学苑"
        //    });
        //    subButton.sub_button.Add(new SingleViewButton()
        //    {
        //        url = "http://ryh.yun-ju.com.cn/UserSchool/Index",
        //        name = "USER学苑"
        //    });
        //    bg.button.Add(subButton);
        //    var subButton2 = new SubButton()
        //    {
        //        name = "专家视角"
        //    };
        //    subButton2.sub_button.Add(new SingleViewButton()
        //    {
        //        url = "http://ryh.yun-ju.com.cn/LiveBroad/MeetingDelivery",
        //        name = "即将开播"
        //    });
        //    subButton2.sub_button.Add(new SingleViewButton()
        //    {
        //        url = "http://ryh.yun-ju.com.cn/LiveBroad/Index",
        //        name = "精彩会议"
        //    });
        //    bg.button.Add(subButton2);
        //    var subButton3 = new SubButton()
        //    {
        //        name = "个人中心"
        //    };
        //    subButton3.sub_button.Add(new SingleViewButton()
        //    {
        //        url = "http://ryh.yun-ju.com.cn/UserInfo/Index",
        //        name = "个人中心"
        //    });
        //    subButton3.sub_button.Add(new SingleViewButton()
        //    {
        //        url = "http://ryh.yun-ju.com.cn/Test/disclaimer.html",
        //        name = "免责声明"
        //    });
        //    bg.button.Add(subButton3);
        //    //object buttonDate = Configuration["WxMent"];

        //    //buttonDate = Newtonsoft.Json.JsonConvert.SerializeObject(buttonDate);
        //    //string access_token = AccessTokenContainer.GetAccessTokenResult(AppId).access_token;
        //    //ButtonGroup bg = new ButtonGroup();
        //    ////单击
        //    var result = Senparc.Weixin.MP.CommonAPIs.CommonApi.CreateMenu(AppId, bg);
        //    return Task.Run(()=>true);
        //}


        #endregion

        #region 获取二维码带参数
        /// <summary>
        /// 
        /// </summary>
        /// <param name="access_token"></param>
        /// <param name="action_info">"action_info": {"scene": {"scene_str": "test"}}</param>
        /// <returns></returns>
        public Task<object> GetQRCodeUrl(string access_token, string scene_str)
        {
            try
            {
                string url = GetQrUrl + "access_token=" + access_token;
                var option ="{\"action_name\": \"QR_LIMIT_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \""+ scene_str + "\"}}}";
                //Dictionary<string, string> option = new Dictionary<string, string>();
                //option.Add("action_name", "QR_LIMIT_STR_SCENE");
                //option.Add("action_info", action_info);

                var result = HttpClientPost(url, option);
                JObject jo = JObject.Parse(result.ToString());
                string ticket = jo["ticket"].ToString();
                //string expire_seconds = jo["expire_seconds"].ToString();
                //string QRurl = jo["url"].ToString();
                //var Showqrcoderesult = HttpCarryAsync(Showqrcode+ticket, HttpMethod.Get).Result;
                //JObject Showqrcodejo = JObject.Parse(Showqrcoderesult.ToString());
                //QRurl=Showqrcodejo[""]
                QrUrlResponse q = new QrUrlResponse() {ticket=ticket,YLurl=Showqrcode+ticket};
                return Task.Run(() => (object)q);
            }
            catch (Exception ex)
            {

                throw new Exception(ex.Message);
            }
           

        }
        public static string HttpClientPost(string url, object datajson)
        {
            HttpClient httpClient = new HttpClient();//http对象
            //表头参数
            httpClient.DefaultRequestHeaders.Accept.Clear();
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            //转为链接需要的格式
            HttpContent httpContent = new StringContent(datajson.ToString());// JsonContent(datajson);
            //请求
            HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
            if (response.IsSuccessStatusCode)
            {
                Task<string> t = response.Content.ReadAsStringAsync();
                if (t != null)
                {
                    return t.Result;
                }
            }
            return "";
        }
        public class JsonContent : StringContent
        {
            public JsonContent(object obj) :
               base(Newtonsoft.Json.JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json")
            { }
        }
        #endregion
    }
}
